from PyQt5.QtWidgets import (QWidget, QLabel, QVBoxLayout, QHBoxLayout,
                             QPushButton, QRadioButton, QButtonGroup, QFrame,
                             QScrollArea, QTextEdit, QCheckBox, QSizePolicy, QApplication)  # 添加 QApplication
from PyQt5.QtCore import Qt
import sys
from io import StringIO
from Data import general
from Data.Chinese import oneClickPublishing


class OutputInterceptor(StringIO):
    def __init__(self, label):
        super().__init__()
        self.label = label
        self.original_stdout = sys.stdout

    def write(self, text):
        super().write(text)
        current_text = self.label.toPlainText()
        
        # 处理ANSI颜色代码
        if '\033[91m' in text:  # 红色
            text = text.replace('\033[91m', '<span style="color: red;">')
            text = text.replace('\033[0m', '</span>')
        elif '\033[92m' in text:  # 绿色
            text = text.replace('\033[92m', '<span style="color: green;">')
            text = text.replace('\033[0m', '</span>')
        elif '\033[93m' in text:  # 黄色
            text = text.replace('\033[93m', '<span style="color: #FFD700;">')
            text = text.replace('\033[0m', '</span>')
        
        if current_text:
            if text.strip():  # 如果不是空行
                self.label.append(text.rstrip())  # 使用append替代setText
                self.label.verticalScrollBar().setValue(  # 自动滚动到底部
                    self.label.verticalScrollBar().maximum()
                )
        else:
            self.label.setText(text.rstrip())
            
        # 确保立即更新UI
        QApplication.processEvents()

    def flush(self):
        pass


class PublishingUI(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()

    def run_process(self):
        self.info_label.clear()

        # 获取复选框状态
        options = {
            'module_number': self.module_number_cb.isChecked(),
            'pdf_conversion': self.pdf_conversion_cb.isChecked(),
            'pdf_hebing': self.pdf_hebing_cb.isChecked(),
            'is_svn': self.select_group.checkedButton().text() == "SVN"  # 添加SVN状态检查
        }

        # 检查是否有选择任何功能
        if not any(options[key] for key in ['module_number', 'pdf_conversion', 'pdf_hebing']):
            self.info_label.setText("请至少选择一个功能！")
            return

        # 设置输出重定向
        output_interceptor = OutputInterceptor(self.info_label)
        sys.stdout = output_interceptor

        try:
            # 调用处理函数，传入SVN状态
            oneClickPublishing.one_click_publishing(options['is_svn'], options)
        except Exception as e:
            self.info_label.setText(f"发生错误: {str(e)}")
        finally:
            sys.stdout = output_interceptor.original_stdout

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(50, 30, 50, 50)

        # 创建标题
        title = QLabel('PDF一键合并')
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet('font-size: 30px; color: #2c3e50; margin: 10px 0 30px 0;')

        # 设置复选框样式
        checkbox_style = """
            QCheckBox {
                font-size: 16px;
                color: #696969;
                padding: 5px;
                spacing: 5px;
            }
            QCheckBox::indicator {
                width: 15px;
                height: 15px;
            }
        """

        # 创建复选框容器
        checkbox_container = QWidget()
        checkbox_layout = QHBoxLayout(checkbox_container)
        checkbox_layout.setAlignment(Qt.AlignCenter)
        checkbox_layout.setSpacing(20)

        # 创建复选框
        self.module_number_cb = QCheckBox("模块编号")
        self.pdf_conversion_cb = QCheckBox("PDF转换")
        self.pdf_hebing_cb = QCheckBox("PDF合并")
        # self.update_content_cb = QCheckBox("更新全文域")
        # self.delete_revision_table_cb = QCheckBox("删除修订记录表")

        checkboxes = [
            self.module_number_cb,
            self.pdf_conversion_cb,
            self.pdf_hebing_cb,
            # self.update_content_cb,
            # self.delete_revision_table_cb
        ]

        for cb in checkboxes:
            cb.setStyleSheet(checkbox_style)
            cb.setChecked(True)
            checkbox_layout.addWidget(cb)

        # 创建单选按钮组
        radio_container = QWidget()
        radio_layout = QHBoxLayout(radio_container)
        radio_layout.setAlignment(Qt.AlignCenter)

        # 设置单选按钮样式
        radio_style = """
            QRadioButton {
                font-size: 16px;
                color: #696969;
                padding: 5px;
                spacing: 10px;
                margin-top: 10px;
            }
            QRadioButton::indicator {
                width: 15px;
                height: 15px;
            }
        """

        # 创建文件选择方式的单选按钮组
        self.select_group = QButtonGroup()
        svn_radio = QRadioButton("SVN")
        not_svn_radio = QRadioButton("非SVN")
        not_svn_radio.setChecked(True)  # 默认选择文件夹

        # 设置单选按钮样式
        svn_radio.setStyleSheet(radio_style)
        not_svn_radio.setStyleSheet(radio_style)

        # 将单选按钮添加到按钮组
        self.select_group.addButton(svn_radio)
        self.select_group.addButton(not_svn_radio)

        # 添加到水平布局
        radio_layout.addWidget(svn_radio)
        radio_layout.addSpacing(50)
        radio_layout.addWidget(not_svn_radio)

        # 创建标题
        title = QLabel('PDF一键合并')
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet('font-size: 30px; color: #2c3e50; margin: 10px;')

        # 创建运行按钮
        run_button = QPushButton('运行')
        run_button.setFixedSize(200, 40)
        run_button.setStyleSheet("""
            QPushButton {
                background-color: #1E90FF;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 16px;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
            QPushButton:pressed {
                background-color: #a93226;
            }
        """)
        run_button.clicked.connect(self.run_process)

        # 添加分割线
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setStyleSheet("background-color: #A9A9A9;")
        line.setFixedHeight(2)

        # 创建信息显示区域
        self.info_label = QTextEdit()
        self.info_label.setReadOnly(True)
        self.info_label.setAcceptRichText(True)  # 添加这行以支持富文本
        self.info_label.setStyleSheet("""
            QTextEdit {
                color: #228B22;
                font-size: 14px;
                font-family: "Microsoft YaHei";
                margin-top: 10px;
                background-color: #F0FFF0;
                border: none;
            }
        """)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidget(self.info_label)
        scroll_area.setWidgetResizable(True)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: #F0FFF0;
            }
            QScrollBar:vertical {
                width: 10px;
                background: #F0FFF0;
            }
            QScrollBar::handle:vertical {
                background: #A9A9A9;
                border-radius: 5px;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
            }
        """)
        scroll_area.setMinimumHeight(300)  # 设置最小高度
        scroll_area.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)  # 设置尺寸策略

        # 添加所有组件到主布局
        layout.addWidget(title)
        layout.addWidget(checkbox_container)
        layout.addWidget(radio_container)  # 添加文件选择方式的单选按钮组
        layout.addSpacing(30)
        layout.addWidget(run_button, alignment=Qt.AlignCenter)
        layout.addSpacing(20)
        layout.addWidget(line)
        layout.addWidget(scroll_area, 1)  # 添加拉伸因子1
        # layout.addStretch()  # 移除这行，让scroll_area自行扩展
